using RabbitMQ.Client;
namespace Beauty.Net.RabbitMQ.Routing
{
    /// <summary>
    /// 路由模式消费者
    /// </summary>
    public class RoutingConsumer<T> : RabbitMQConsumerBase<T>
    {
        private readonly string[] _routingKeys;

        public RoutingConsumer(IRabbitMQConnectionManager connectionManager,
                              string exchangeName,
                              string queueName,
                              string routingKey,
                              MessageHandler<T> messageHandler,
                              bool autoAck = false)
            : this(connectionManager, exchangeName, queueName, new[] { routingKey }, messageHandler, autoAck)
        {}

        public RoutingConsumer(IRabbitMQConnectionManager connectionManager,
                              string exchangeName,
                              string queueName,
                              string[] routingKeys,
                              MessageHandler<T> messageHandler,
                              bool autoAck = false)
            : base(connectionManager, exchangeName, queueName, routingKeys[0], messageHandler, autoAck)
        {
            _routingKeys = routingKeys;
        }

        protected override void SetupExchangeAndQueue()
        {
            if (_channel == null) throw new InvalidOperationException("Channel not initialized");
            
            // 声明直接交换机
            _channel.ExchangeDeclare(exchange: ExchangeName,
                                   type: ExchangeType.Direct,
                                   durable: true,
                                   autoDelete: false,
                                   arguments: null);

            // 声明队列
            _channel.QueueDeclare(queue: QueueName,
                                durable: true,
                                exclusive: false,
                                autoDelete: false,
                                arguments: null);

            // 将队列绑定到交换机的每个路由键
            foreach (var routingKey in _routingKeys)
            {
                _channel.QueueBind(queue: QueueName,
                                  exchange: ExchangeName,
                                  routingKey: routingKey);
            }
        }
    }
}